﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AutoMapper;
using DTO;


namespace Data {
    public class HoaDonBanSachRepository {
        /// <summary>
        /// them vao phieu thu moi
        /// </summary>
        /// <param name="newValue">hoa don ban sach</param>
        /// <returns>gia tri tra ve la id hoa don moi them vao</returns>
        public int InsertNewHoaDonBanSach(HoaDonBanSachDTO newValue) {
            try {
                QuanLyNhaSachEntities context = new QuanLyNhaSachEntities();
                HOADONBANSACH bill = new HOADONBANSACH();

                Mapper.CreateMap<HoaDonBanSachDTO, HOADONBANSACH>();
                bill = Mapper.Map<HoaDonBanSachDTO, HOADONBANSACH>(newValue);

                context.AddToHoaDonBanSachList(bill);
                context.SaveChanges();

                int hoaDonID = (from hoaDonItem in context.HoaDonBanSachList
                                   select hoaDonItem.IDHoaDonBanSach).Max();
                return hoaDonID;
            }
            catch {
                return 0;
            }         
        }

        public string CreateMaHoaDonBanSach() {
            //giay gia tri index ra
            QuanLyNhaSachEntities context = new QuanLyNhaSachEntities();
            //indentify ID
            var maxID = (from max in context.GetIndentity("HOADONBANSACH")
                         select max.CurrentIndentity).FirstOrDefault();
            if (maxID == 1)
                maxID = 0;

            return "HD" + (maxID + 1);            
        }
    }
}
